package com.coalmine.api.controller;


import com.alibaba.fastjson.JSON;
import com.coalmine.api.domain.ApiDatasource;
import com.coalmine.api.service.IApiDatasourceService;
import com.coalmine.api.util.JdbcUtil;
import com.coalmine.common.annotation.Log;
import com.coalmine.common.core.controller.BaseController;
import com.coalmine.common.core.domain.AjaxResult;
import com.coalmine.common.core.page.TableDataInfo;
import com.coalmine.common.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.web.bind.annotation.RestController;


/**
 * <p>
 *  api数据源信息 前端控制器
 * </p>
 *
 * @author 尚郑
 * @since 2022-04-01
 */
@Api(value="数据源管理API",tags={"API数据源管理接口"})
@RestController
@RequestMapping("/api/datasource")
public class ApiDatasourceController  extends BaseController {

    @Autowired
    IApiDatasourceService apiDatasourceService;

    /**
     * 新增数据源
     */
    @PreAuthorize("@ss.hasPermi('api:datasource:add')")
    @ApiOperation("新增数据源")
    @Log(title = "数据源管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Valid ApiDatasource apiDatasource) {
        apiDatasource.setCreateBy(getUsername());
        apiDatasource.setUpdateBy(getUsername());
        return toAjax(apiDatasourceService.add(apiDatasource));
    }

    @PreAuthorize("@ss.hasPermi('api:datasource:list')")
    @ApiOperation("获取所有数据源")
    @GetMapping("/getAll")
    public TableDataInfo getAll() {
        startPage();
        List<ApiDatasource> list = apiDatasourceService.getAll();
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('api:datasource:detail')")
    @ApiOperation("根据id获取数据源详情")
    @GetMapping("/detail/{id}")
    public AjaxResult detail(@PathVariable String id) {
        ApiDatasource apiDatasource = apiDatasourceService.detail(id);
        if(apiDatasource == null){
            return AjaxResult.error("未查询到id为"+id+"的数据");
        }
        return AjaxResult.success(apiDatasource);
    }

    @PreAuthorize("@ss.hasPermi('api:datasource:remove')")
    @ApiOperation("根据id删除数据源")
    @Log(title = "数据源管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable String id) {
        return toAjax(apiDatasourceService.delete(id));
    }

    @PreAuthorize("@ss.hasPermi('api:datasource:edit')")
    @ApiOperation("更新数据源")
    @Log(title = "数据源管理", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult update(ApiDatasource apiDatasource) {
        apiDatasource.setUpdateBy(getUsername());
        return toAjax(apiDatasourceService.update(apiDatasource));
    }

    @PreAuthorize("@ss.hasPermi('api:datasource:connect')")
    @ApiOperation("测试数据源连接")
    @PostMapping("/connect")
    public AjaxResult connect(@RequestBody @Valid ApiDatasource apiDatasource) {
        Connection connection = null;
        try {
            connection = JdbcUtil.getConnection(apiDatasource);
            return AjaxResult.success("连接成功！");
        } catch (Exception e) {
            return AjaxResult.error("连接异常，请检查数据源连接");
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    AjaxResult.error("关闭连接异常");
                }
            }
        }
    }

    @PreAuthorize("@ss.hasPermi('api:datasource:export')")
    @ApiOperation("数据源导出")
    @Log(title = "数据源管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@RequestParam("ids") String ids, HttpServletResponse response) {
        List<String> collect = Arrays.asList(ids.split(","));
        List<ApiDatasource> list = apiDatasourceService.selectBatch(collect);
        String s = JSON.toJSONString(list);
        response.setContentType("application/x-msdownload;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=datasource.json");
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            os.write(s.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @PreAuthorize("@ss.hasPermi('api:datasource:import')")
    @ApiOperation("数据源导入")
    @Log(title = "数据源管理", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/import", produces = "application/json;charset=UTF-8")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        String s = IOUtils.toString(file.getInputStream(), StandardCharsets.UTF_8);
        if (StringUtils.isBlank(s)) {
            return AjaxResult.error("文件不能为空");
        }
        List<ApiDatasource> list = JSON.parseArray(s, ApiDatasource.class);
        list.forEach((ApiDatasource apiDatasource) -> {
                    apiDatasource.setCreateBy(getUsername());
                    apiDatasource.setCreateTime(new Date());
                }
        );
        apiDatasourceService.insertBatch(list);
        return AjaxResult.success("导入数据源成功");

    }

}
